import { defineStore } from 'pinia';
import { message } from 'ant-design-vue';

export type BuildStatus = 'idle' | 'start' | 'running' | 'finish' | 'error';

interface BuildStateEntry {
  status: BuildStatus;
  logs: string[];
  lastMessage?: string;
}

export const useSSEStore = defineStore('sseStore', {
  state: () => ({
    buildEventSourceByAppId: {} as Record<string, EventSource | null>,
    buildStateByAppId: {} as Record<string, BuildStateEntry>,
  }),
  actions: {
    ensureBuildSSE(appId: string) {
      if (!appId) return;
      const existing = this.buildEventSourceByAppId[appId];
      if (existing && existing.readyState !== EventSource.CLOSED) {
        return;
      }

      const url = `http://localhost:8080/api/sse/connect/${appId}`;
      try {
        const es = new EventSource(url, { withCredentials: true });

        if (!this.buildStateByAppId[appId]) {
          this.buildStateByAppId[appId] = { status: 'idle', logs: [] };
        }

        es.onopen = () => {
          this.buildStateByAppId[appId].status = 'running';
          message.success(`已连接构建进度 (${appId})`);
        };

        es.onerror = (ev) => {
          // 若服务端正常关闭（完成构建后断开），不标记为 error
          if (es.readyState === EventSource.CLOSED) {
            if (this.buildStateByAppId[appId]?.status !== 'finish') {
              this.buildStateByAppId[appId].status = 'error';
            }
            this.buildEventSourceByAppId[appId] = null;
             
            console.warn('[SSE] 连接已关闭');
            message.warning(`构建进度连接已关闭 (${appId})`);
            return;
          }
          this.buildStateByAppId[appId].status = 'error';
           
          console.warn('[SSE] 连接错误', ev);
          message.error(`构建进度连接错误 (${appId})`);
        };

        es.onmessage = (event: MessageEvent) => {
          try {
            const payload = JSON.parse(event.data || '{}');
            const eventMsg: string = (payload.eventMsg || '').toLowerCase();
            const data: string = payload.data ?? '';

            switch (eventMsg) {
              case 'start':
                this.buildStateByAppId[appId].status = 'start';
                this.buildStateByAppId[appId].logs.push(data);
                this.buildStateByAppId[appId].lastMessage = data;
                message.info('开始构建 Vue 项目...');
                break;
              case 'running':
                this.buildStateByAppId[appId].status = 'running';
                if (data) this.buildStateByAppId[appId].logs.push(data);
                this.buildStateByAppId[appId].lastMessage = data;
                message.info(data || '构建进行中...');
                break;
              case 'finish':
                this.buildStateByAppId[appId].status = 'finish';
                if (data) this.buildStateByAppId[appId].logs.push(data);
                this.buildStateByAppId[appId].lastMessage = data;
                message.success('构建完成');
                break;
              default:
                // 未指定 eventMsg，当作普通日志
                if (data) this.buildStateByAppId[appId].logs.push(data);
                this.buildStateByAppId[appId].lastMessage = data;
                if (data) message.info(data);
                break;
            }
          } catch (e) {
             
            console.log('[SSE][message]', event.data);
          }
        };

        this.buildEventSourceByAppId[appId] = es;
      } catch (error) {
         
        console.error('初始化构建进度 SSE 失败', error);
      }
    },

    closeBuildSSE(appId: string) {
      const es = this.buildEventSourceByAppId[appId];
      if (es) {
        es.close();
        this.buildEventSourceByAppId[appId] = null;
      }
    },
  },
}); 